<?php

namespace app\controller;

use app\BaseController;
use app\ErrorCode;
use app\exception\ApiException;
use app\Request;
use app\service\PasswordMixService;
use app\service\AdminService;

class AdminController
{
    public function getList(Request $request)
    {
        $username = $request->post('username');
        $page = $request->post('page');
        $pageSize = $request->post('pageSize');
        $result = AdminService::getInstance()->getAdminList($username, $page, $pageSize);
        return jsonResponse($result);
    }
    public function create(Request $request)
    {
        $username = $request->post("username");
        $password = $request->post("password");
        $phone = $request->post("phone");
        $email = $request->post("email");
        $avatar = $request->post("avatar");
        $type = $request->post("type");

        if (!$username || !$password) {
            throw new ApiException("用户名或密码不能为空", ErrorCode::BUSINESS);
        }

        $passMixSalt = PasswordMixService::getInstance()->mixSalt($password);
        $pass = $passMixSalt["pass"];
        $salt = $passMixSalt["salt"];

        $result = AdminService::getInstance()->createAdmin($username, $phone, $email, $type, $avatar, $pass, $salt);
        return jsonResponse($result);
    }

    public function update(Request $request)
    {
        $id = $request->post("id");
        $username = $request->post("username");
        $password = $request->post("password");
        $phone = $request->post("phone");
        $email = $request->post("email");
        $type = $request->post("type");

        $result = AdminService::getInstance()->updateAdmin($id, $username, $password, $phone, $email, $type);
        return jsonResponse($result);
    }

    public function  delete(Request $request)
    {
        $id = $request->post("id");
        $result = AdminService::getInstance()->deleteAdmin($id);
        return jsonResponse($result);
    }
}